package com.whiteape.book.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.whiteape.book.R;
import com.whiteape.book.WaApp;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.ui.base.BaseTabActivity;
import com.whiteape.book.ui.fragment.BaseFileFragment;
import com.whiteape.book.ui.fragment.FileCategoryFragment;
import com.whiteape.book.ui.fragment.LocalBookFragment;
import com.whiteape.book.utils.JumpPermissionManagement;
import com.whiteape.book.utils.MD5Utils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;


/**
 * Created by newbiechen on 17-5-27.
 */

public class FileSystemActivity extends BaseTabActivity {
    private static final String TAG = "FileSystemActivity";

    @BindView(R.id.file_system_cb_selected_all)
    CheckBox mCbSelectAll;
    @BindView(R.id.file_system_btn_op1)
    Button mBtnOp1;
    @BindView(R.id.file_system_btn_op2)
    Button mBtnOp2;

    public static final String FILE_TYPE_KEY = "file_type_key";

    private LocalBookFragment mLocalFragment;
    private FileCategoryFragment mCategoryFragment;
    private BaseFileFragment mCurFragment;

    int fileType = LoadFileType.FILE_TYPE_BOOK;
    private BaseFileFragment.OnFileCheckedListener mListener = new BaseFileFragment.OnFileCheckedListener() {
        @Override
        public void onItemCheckedChange(boolean isChecked) {
            changeMenuStatus();
        }

        @Override
        public void onCategoryChanged() {
            //状态归零
            mCurFragment.setCheckedAll(false);
            //改变菜单
            changeMenuStatus();
            //改变是否能够全选
            changeCheckedAllStatus();
        }
    };

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        fileType = getIntent().getIntExtra(FILE_TYPE_KEY, LoadFileType.FILE_TYPE_BOOK);
    }


    @Override
    protected List<Fragment> createTabFragments() {
        mLocalFragment = LocalBookFragment.newInstance(fileType);
        mCategoryFragment = FileCategoryFragment.newInstance(fileType);
        return Arrays.asList(mLocalFragment, mCategoryFragment);
    }

    @Override
    protected List<String> createTabTitles() {
        return Arrays.asList("智能导入", "手机目录");
    }

    @Override
    protected int getContentId() {
        return R.layout.activity_file_system;
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        getSupportActionBar().setTitle("本机导入");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mCbSelectAll.setOnClickListener(
                (view) -> {
                    //设置全选状态
                    boolean isChecked = mCbSelectAll.isChecked();
                    mCurFragment.setCheckedAll(isChecked);
                    //改变菜单状态
                    changeMenuStatus();
                }
        );

        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mCurFragment = mLocalFragment;
                } else {
                    mCurFragment = mCategoryFragment;
                }
                //改变菜单状态
                changeMenuStatus();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mBtnOp2.setOnClickListener((view -> {
                    List<File> files = mCurFragment.getCheckedFiles();
                    setResult(RESULT_OK, new Intent().putExtra("data", (Serializable)files));
                    finish();
                })
        );

//        mBtnOp2.setOnClickListener(
//                (v) -> {
//                    //获取选中的文件
//                    List<File> files = mCurFragment.getCheckedFiles();
//                    //转换成CollBook,并存储
//                    List<CollectionMediaBean> collBooks = convertCollBook(files);
//                    BookRepository.getInstance()
//                            .saveCollBooks(collBooks);
//                    //设置HashMap为false
//                    mCurFragment.setCheckedAll(false);
//                    //改变菜单状态
//                    changeMenuStatus();
//                    //改变是否可以全选
//                    changeCheckedAllStatus();
//                    //提示加入书架成功
//                    ToastUtils.show(getResources().getString(R.string.nb_file_add_succeed,collBooks.size()));
//
//                }
//        );

//        mBtnOp1.setOnClickListener(
//                (v) -> {
//                    //弹出，确定删除文件吗。
//                    new AlertDialog.Builder(this)
//                            .setTitle("删除文件")
//                            .setMessage("确定删除文件吗?")
//                            .setPositiveButton(getResources().getString(R.string.nb_common_sure), new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    //删除选中的文件
//                                    mCurFragment.deleteCheckedFiles();
//                                    //提示删除文件成功
//                                    ToastUtils.show("删除文件成功");
//                                }
//                            })
//                            .setNegativeButton(getResources().getString(R.string.nb_common_cancel), null)
//                            .show();
//                }
//        );

        mLocalFragment.setOnFileCheckedListener(mListener);
        mCategoryFragment.setOnFileCheckedListener(mListener);
    }

    @Override
    protected void initView() {
        super.initView();
        mTlIndicator.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorAccent));
        mTlIndicator.setTabTextColors(Color.BLACK, getResources().getColor(R.color.colorAccent));

//        getWindow().getDecorView().setBackgroundColor(WaApp.getInstance().getResources().getColor(R.color.statusBarColor));
        if (fileType == LoadFileType.FILE_TYPE_BOOK) {
            mBtnOp2.setText(getString(R.string.wa_file_add_shelf));
        } else if (fileType == LoadFileType.FILE_TYPE_SITE_SOURCE) {
            mBtnOp2.setText(getString(R.string.wa_file_add_site_source));
        } else if (fileType == LoadFileType.FILE_TYPE_TYPEFACE) {
            mBtnOp2.setText(getString(R.string.wa_file_select_typeface));
        }else if (fileType == LoadFileType.FILE_TYPE_REPLACE_RULE){
            mBtnOp2.setText(getString(R.string.wa_file_select_replace_rule));
        }
    }

    @Override
    protected void startLogic() {
        super.startLogic();
        mCurFragment = mLocalFragment;
    }

    /**
     * 将文件转换成CollBook
     *
     * @param files:需要加载的文件列表
     * @return
     */
    private List<CollectionMediaBean> convertCollBook(List<File> files) {
        List<CollectionMediaBean> collBooks = new ArrayList<>(files.size());
        for (File file : files) {
            //判断文件是否存在
            if (!file.exists()) continue;

            CollectionMediaBean collBook = new CollectionMediaBean();
            collBook.setId(MD5Utils.strToMd5By16(file.getAbsolutePath()));
            collBook.setTitle(file.getName().replace(".txt", ""));
            collBook.setAuthor("");
//            collBook.setShortIntro("无");
//            collBook.setCover(file.getAbsolutePath());
            collBook.setIfLocal(true);
            collBook.setLastChapter("开始阅读");
            collBook.setLastUpdated(StringUtils.dateConvert(file.lastModified(), WaConstants.FORMAT_BOOK_DATE));
            collBook.setLastRead(StringUtils.
                    dateConvert(System.currentTimeMillis(), WaConstants.FORMAT_BOOK_DATE));
            collBooks.add(collBook);
        }
        return collBooks;
    }

    /**
     * 改变底部选择栏的状态
     */
    private void changeMenuStatus() {

        //点击、删除状态的设置
        if (mCurFragment.getCheckedCount() == 0) {
            if (fileType == LoadFileType.FILE_TYPE_BOOK) {
                mBtnOp2.setText(getString(R.string.wa_file_add_shelf));
            } else if (fileType == LoadFileType.FILE_TYPE_SITE_SOURCE) {
                mBtnOp2.setText(getString(R.string.wa_file_add_site_source));
            }
            //设置某些按钮的是否可点击
            setMenuClickable(false);

            if (mCbSelectAll.isChecked()) {
                mCurFragment.setChecked(false);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }

        } else {
            if (fileType == LoadFileType.FILE_TYPE_BOOK) {
                mBtnOp2.setText(getString(R.string.wa_file_add_shelves, mCurFragment.getCheckedCount()));
            } else if (fileType == LoadFileType.FILE_TYPE_SITE_SOURCE) {
                mBtnOp2.setText(getString(R.string.wa_file_add_site_source_with_num, mCurFragment.getCheckedCount()));
            }
            setMenuClickable(true);

            //全选状态的设置

            //如果选中的全部的数据，则判断为全选
            if (mCurFragment.getCheckedCount() == mCurFragment.getCheckableCount()) {
                //设置为全选
                mCurFragment.setChecked(true);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }
            //如果曾今是全选则替换
            else if (mCurFragment.isCheckedAll()) {
                mCurFragment.setChecked(false);
                mCbSelectAll.setChecked(mCurFragment.isCheckedAll());
            }
        }

        //重置全选的文字
        if (mCurFragment.isCheckedAll()) {
            mCbSelectAll.setText("取消");
        } else {
            mCbSelectAll.setText("全选");
        }

    }

    private void setMenuClickable(boolean isClickable) {

        //设置是否可删除
        mBtnOp1.setEnabled(isClickable);
        mBtnOp1.setClickable(isClickable);

        //设置是否可添加书籍
        mBtnOp2.setEnabled(isClickable);
        mBtnOp2.setClickable(isClickable);
    }

    /**
     * 改变全选按钮的状态
     */
    private void changeCheckedAllStatus() {
        //获取可选择的文件数量
        int count = mCurFragment.getCheckableCount();

        //设置是否能够全选
        if (count > 0) {
            mCbSelectAll.setClickable(true);
            mCbSelectAll.setEnabled(true);
        } else {
            mCbSelectAll.setClickable(false);
            mCbSelectAll.setEnabled(false);
        }
    }
}
